from django.db import models
from users.models import User

class TechInsight(models.Model):
    """技术洞察模型"""
    
    # 基本信息
    title = models.CharField('标题', max_length=200)
    industry = models.CharField('产业', max_length=100)
    keyword = models.CharField('关键词', max_length=100)
    
    # 内容字段
    insight_content = models.TextField('洞察内容')
    trend_analysis = models.TextField('趋势分析', null=True, blank=True)
    tech_analysis = models.TextField('技术分析', null=True, blank=True)
    market_analysis = models.TextField('市场分析', null=True, blank=True)
    
    # 元数据
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='创建者')
    
    # 状态标记
    is_active = models.BooleanField('是否有效', default=True)
    
    class Meta:
        db_table = 'tech_insights'
        verbose_name = '技术洞察'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']
        # 添加联合索引
        indexes = [
            models.Index(fields=['industry', 'keyword']),
            models.Index(fields=['user', '-created_at'])
        ]
        
    def __str__(self):
        return f"{self.industry}-{self.keyword}"

class InsightReference(models.Model):
    """技术洞察参考文献"""
    insight = models.ForeignKey(
        TechInsight,
        on_delete=models.CASCADE,
        related_name='references',
        verbose_name='技术洞察'
    )
    title = models.CharField('文章标题', max_length=255)
    content = models.TextField('文章内容')

    class Meta:
        db_table = 'tech_insight_references'
        verbose_name = '参考文献'
        verbose_name_plural = verbose_name

class IndustryKeyword(models.Model):
    """行业关键词配置"""
    industry = models.CharField('行业', max_length=100, unique=True)
    keywords = models.JSONField('关键词列表', default=list)
    last_sync_at = models.DateTimeField('上次同步时间', null=True)
    is_active = models.BooleanField('是否启用', default=True)

    class Meta:
        db_table = 'industry_keywords'
        verbose_name = '行业关键词'
        verbose_name_plural = verbose_name

class InsightTask(models.Model):
    """技术洞察任务"""
    STATUS_CHOICES = [
        ('pending', '待处理'),
        ('processing', '处理中'),
        ('completed', '已完成'),
        ('failed', '失败')
    ]

    industry = models.CharField('行业', max_length=100)
    keyword = models.CharField('关键词', max_length=100)
    status = models.CharField(
        '状态',
        max_length=20,
        choices=STATUS_CHOICES,
        default='pending'
    )
    error_message = models.TextField('错误信息', null=True, blank=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    completed_at = models.DateTimeField('完成时间', null=True)

    class Meta:
        db_table = 'insight_tasks'
        ordering = ['-created_at']
        verbose_name = '洞察任务'
        verbose_name_plural = verbose_name
